package com.zzh.camera2.utils

import android.content.Context
import android.graphics.*
import android.renderscript.*
import java.io.ByteArrayOutputStream
import java.io.IOException


/**
 * @author ：zuhui.zhang
 * time ： 2021/4/23 15:14
 */
class NV21ToBitmap(context: Context?) {
    private var rs: RenderScript? = null
    private var yuvToRgbIntrinsic: ScriptIntrinsicYuvToRGB? = null
    private var yuvType: Type.Builder? = null
    private var rgbaType: Type.Builder? = null
    private var input: Allocation? = null
    private var out: Allocation? = null

    init {
        rs = RenderScript.create(context)
        yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs))
    }

    @Synchronized
    fun nv21ToBitmap(nv21: ByteArray, width: Int, height: Int): Bitmap? {
        if (yuvType == null) {
            yuvType = Type.Builder(rs, Element.U8(rs)).setX(nv21.size)
            input = Allocation.createTyped(rs, yuvType!!.create(), Allocation.USAGE_SCRIPT)
            rgbaType = Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height)
            out = Allocation.createTyped(rs, rgbaType!!.create(), Allocation.USAGE_SCRIPT)
        }
        input!!.copyFrom(nv21)
        yuvToRgbIntrinsic!!.setInput(input)
        yuvToRgbIntrinsic!!.forEach(out)
        val bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        out!!.copyTo(bmpout)
        return bmpout
    }


    fun nv21ToBitmap2(nv21: ByteArray, width: Int, height: Int): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            val image = YuvImage(nv21, ImageFormat.NV21, width, height, null)
            val stream = ByteArrayOutputStream()
            image.compressToJpeg(Rect(0, 0, width, height), 80, stream)
            bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size())
            stream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return bitmap
    }
}